import router from '@/router'
import { ElMessageBox } from 'element-plus'
import { login, logout, getInfo } from '@/api/sys/login'
import { getToken, setToken, removeToken, tokenKey } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg' 

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(tokenKey.access), 
      id: '',
      name: '',
      username: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    getters: {
      userInfo: (state) => ({
        id: state.id, 
        name: state.name, 
        username: state.username, 
        avatar: state.avatar, 
        roles: state.roles, 
        permissions: state.permissions  
      })
    },
    actions: {
      // 登录 
      login(userInfo) {
        const username = userInfo.username.trim() 
        const password = userInfo.password  
        const captcha = userInfo.captcha  
        const id = userInfo.id  
        return new Promise((resolve, reject) => {
          login(username, password, captcha, id).then(res => {
            setToken(tokenKey.access,  res.data.access) 
            setToken(tokenKey.refresh,  res.data.refresh) 
            this.token  = res.data.access  
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息 
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.data.user  
            const avatar = (user.avatar  == "" || user.avatar  == null) ? defAva : import.meta.env.VITE_APP_BASE_API  + user.avatar; 
 
            if (res.data.roles  && res.data.roles.length  > 0) {
              this.roles  = res.data.roles  
              this.permissions  = res.data.permissions  
            } else {
              this.roles  = ['ROLE_DEFAULT']
            }
            this.id  = user.id  
            this.name  = user.name  
            this.username  = user.username  
            this.avatar  = avatar;
            
            /* 初始密码提示 */
            if(res.isDefaultModifyPwd)  {
              ElMessageBox.confirm(' 您的密码还是初始密码，请修改密码！', '安全提示', { 
                confirmButtonText: '确定', 
                cancelButtonText: '取消', 
                type: 'warning' 
              }).then(() => {
                router.push({  name: 'Profile', params: { activeTab: 'resetPwd' } })
              }).catch(() => {})
            }
            /* 过期密码提示 */
            if(!res.isDefaultModifyPwd  && res.isPasswordExpired)  {
              ElMessageBox.confirm(' 您的密码已过期，请尽快修改密码！', '安全提示', { 
                confirmButtonText: '确定', 
                cancelButtonText: '取消', 
                type: 'warning' 
              }).then(() => {
                router.push({  name: 'Profile', params: { activeTab: 'resetPwd' } })
              }).catch(() => {})
            }
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统 
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(()  => {
            this.token  = ''
            this.roles  = []
            this.permissions  = []
            removeToken(tokenKey.access) 
            removeToken(tokenKey.refresh) 
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 前端退出系统 
      async fadeOut() {
        try {
          return await new Promise((resolve, reject) => {
            this.token  = ''
            this.roles  = []
            this.permissions  = []
            removeToken(tokenKey.access) 
            removeToken(tokenKey.refresh) 
            resolve()
          })
        } catch (error) {
          reject(error)
        }
      }
    }
  })
 
export default useUserStore 